package org.dbview.controller;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;

import org.dbview.model.SimpleResponse;
import org.dbview.model.TDictionaryModule;
import org.dbview.model.TDictionaryRelation;
import org.dbview.model.ViewDictionary;
import org.dbview.service.IDictionaryModuleService;
import org.dbview.service.IDictionaryRelationService;
import org.dbview.service.IViewDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ConfigModuleRelationController {
	@Autowired
	private IViewDictionaryService viewDictionaryService;
	@Autowired
	private IDictionaryModuleService dictionaryModuleService;
	@Autowired
	private IDictionaryRelationService dictionaryRelationService;

	@RequestMapping(value = "getModuleList.do")
	@ResponseBody
	public List<TDictionaryModule> getModuleList() {
		return dictionaryModuleService.getAllViewModule();
	}
	
	@RequestMapping(value = "getTableList.do")
	@ResponseBody
	public List<TDictionaryRelation> getTableList(@RequestBody String moduleId) {
		return dictionaryRelationService.getListByModuleId(new BigDecimal(moduleId));
	}
	
	@RequestMapping(value = "getAllTableList.do")
	@ResponseBody
	public List<ViewDictionary> getAllTableList() {
		return viewDictionaryService.getAllTable();
	}
	
	@RequestMapping(value = "addRelation.do")
	@ResponseBody
	public SimpleResponse addRelation(@RequestBody TDictionaryRelation tDictionaryRelation) {
		List<TDictionaryRelation> list = 
				dictionaryRelationService.getListByModuleId(tDictionaryRelation.getModuleId());
		for (TDictionaryRelation temp : list) {
			if (temp.getTableName().equals(tDictionaryRelation.getTableName())) {
				return new SimpleResponse(Boolean.FALSE, "对应关系已经存在");
			}
		}
		tDictionaryRelation.setStatementTime(new Date(System.currentTimeMillis()));
		if (dictionaryRelationService.addRelation(tDictionaryRelation) > 0) {
			return new SimpleResponse(Boolean.TRUE);
		} else {
			return new SimpleResponse(Boolean.FALSE, "写入数据库失败");
		}
	}
	
	@RequestMapping(value = "delRelation.do")
	@ResponseBody
	public SimpleResponse getAllTableList(@RequestBody TDictionaryRelation tDictionaryRelation) {
		 if (dictionaryRelationService.delRelation(tDictionaryRelation) > 0) {
			 return new SimpleResponse(Boolean.TRUE);
		 } else {
			 return new SimpleResponse(Boolean.FALSE, "删除数据库失败");
		 }
	}
}
